﻿//// Copyright (c) Microsoft Corporation. All rights reserved

(function () {
    "use strict";

    var allJoyn = Windows.Devices.AllJoyn;
    var secureInterface = com.microsoft.Samples.SecureInterface;

    var page = WinJS.UI.Pages.define("/html/scenario1.html", {
        ready: function (element, options) {
            scenarioInit();
        },
        unload: function (element, options) {
            scenarioCleanup();
        }
    });

    var isBusAttachmentConnected = false;
    var key, producer, busAttachment;

    function scenarioInit() {
        producerOptions.style.display = "none";
        launchButton.onclick = launchButtonClickHandler;
        upperCaseSwitch.winControl.checked = AppData.secureInterfaceProperties.isUpperCaseEnabled;
        upperCaseSwitch.onchange = upperCaseSwitchChangeHandler;
        sendSignalButton.onclick = sendSignalButtonClickHandler;
    }

    function scenarioCleanup() {
        if (producer != null) {
            producer.service.onconcatenatecalled = null;
            producer.service.ongetisuppercaseenabledrequested = null;
            producer.service.onsetisuppercaseenabledrequested = null;
            producer.stop();
        }
        if (busAttachment != null) {
            busAttachment.onstatechanged = null;
            busAttachment.onauthenticationcomplete = null;
            busAttachment.oncredentialsrequested = null;
            busAttachment.disconnect();
            isBusAttachmentConnected = false;
        }
    }

    function launchButtonClickHandler() {
        if (isBusAttachmentConnected) {
            reportStatus("Already launched.");
        } else {
            reportStatus("Launching...");

            busAttachment = new allJoyn.AllJoynBusAttachment();
            busAttachment.onstatechanged = stateChangedHandler;
            busAttachment.authenticationMechanisms.clear();
            busAttachment.authenticationMechanisms.append(allJoyn.AllJoynAuthenticationMechanism.ecdheSpeke);
            busAttachment.onauthenticationcomplete = authenticationCompleteHandler;
            busAttachment.oncredentialsrequested = credentialsRequestedHandler;

            // Optional - Populate About data for the producer.
            busAttachment.aboutData.defaultManufacturer = "Contoso";
            busAttachment.aboutData.supportUrl = new Windows.Foundation.Uri("http://www.contoso.com/support");
            busAttachment.aboutData.modelNumber = "ContosoTestModel";
            busAttachment.aboutData.defaultDescription = "A secure AllJoyn sample";

            // Generate the one-time 6-digit numeric pre-shared key.
            key = Math.floor((Math.random() * 1000000) + 1);
            keyDisplay.textContent = key;

            // Initialize the producer object generated by the AllJoynCodeGenerator tool.
            producer = new secureInterface.SecureInterfaceProducer(busAttachment);

            // Instantiate SecureInterfaceService which will handle the concatenation method calls.
            producer.service = new secureInterface.SecureInterfaceServiceEventAdapter();
            producer.service.onconcatenatecalled = concatenateCalledHandler;
            producer.service.ongetisuppercaseenabledrequested = getIsUpperCaseEnabledRequestedHandler;
            producer.service.onsetisuppercaseenabledrequested = setIsUpperCaseEnabledRequestedHandler;

            // Start advertising the service.
            producer.start();
        }
    }

    function upperCaseSwitchChangeHandler(args) {
        AppData.secureInterfaceProperties.isUpperCaseEnabled = args.target.winControl.checked;
        if (producer != null) {
            producer.emitIsUpperCaseEnabledChanged();
        }
    }

    function sendSignalButtonClickHandler() {
        if (producer != null) {
            var message = signalText.value;
            if ((typeof message === 'undefined') || (message == null) || (!/\S/.test(message))) {
                reportError("No text entered.")
            } else {
                producer.signals.textSent(message);
                reportStatus("Signal sent.");
            }
        }
    }

    function stateChangedHandler(args) {
        switch (args.detail[0].state) {
            case allJoyn.AllJoynBusAttachmentState.disconnected:
                reportStatus("Disconnected from the AllJoyn bus attachment with AllJoyn status: 0x" + args.detail[0].status.toString(16));
                isBusAttachmentConnected = false;
                producerOptions.style.display = "none";
                break;
            case allJoyn.AllJoynBusAttachmentState.connected:
                reportStatus("Launched.");
                isBusAttachmentConnected = true;
                producerOptions.style.display = "block";
                break;
        }
    }

    function authenticationCompleteHandler(args) {
        if (args.detail[0].succeeded) {
            reportStatus("Authentication was successful.");
        } else {
            reportError("Authentication failed.");
        }
    }

    function credentialsRequestedHandler(args) {
        if (args.detail[0].credentials.authenticationMechanism == allJoyn.AllJoynAuthenticationMechanism.ecdheSpeke) {
            args.detail[0].credentials.passwordCredential.password = key;
        } else {
            reportError("Unexpected authentication mechanism.");
        }
    }

    function concatenateCalledHandler(args) {
        reportStatus("Concatenation request recieved for \"" + args.detail[0].inStr1 + "\" and \"" + args.detail[0].inStr2 + "\".");

        if (AppData.secureInterfaceProperties.isUpperCaseEnabled) {
            args.detail[0].result = secureInterface.SecureInterfaceConcatenateResult.createSuccessResult(args.detail[0].inStr1.toUpperCase() + args.detail[0].inStr2.toUpperCase());
        } else {
            args.detail[0].result = secureInterface.SecureInterfaceConcatenateResult.createSuccessResult(args.detail[0].inStr1 + args.detail[0].inStr2);
        }
    }

    function getIsUpperCaseEnabledRequestedHandler(args) {
        args.detail[0].result = secureInterface.SecureInterfaceGetIsUpperCaseEnabledResult.createSuccessResult(AppData.secureInterfaceProperties.isUpperCaseEnabled);
    }

    function setIsUpperCaseEnabledRequestedHandler(args) {
        AppData.secureInterfaceProperties.isUpperCaseEnabled = args.detail[0].value;
        upperCaseSwitch.winControl.checked = args.detail[0].value;
        args.detail[0].result = secureInterface.SecureInterfaceSetIsUpperCaseEnabledResult.createSuccessResult();
    }

    function reportStatus(message) {
        WinJS.log && WinJS.log(message, "sample", "status");
    }

    function reportError(message) {
        WinJS.log && WinJS.log(message, "sample", "error");
    }
})();
